﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Castle.Core.Logging;
using ComponentFactory.Krypton.Toolkit;

namespace TVN.ShopMan.ApplicationInterface.AppForms
{
    using TVN.Common.Interfaces;
    using TVN.ShopMan.ActiveModels;

    /// <summary>
    /// Displays a combo box of repositories, and user select one.
    /// </summary>
    public partial class RepositorySelectionForm : Form
    {
        private static readonly ILogger _logger = Program.Logger.CreateChildLogger("RepositorySelectionForm");
        private IRepository<Repository> repositoryRepository = null;
        private IList<Repository> listOfRepositories = null;

        private Repository selectedRepository = null;
        /// <summary>
        /// Returns the repository user selected after click OK button.
        /// </summary>
        public Repository SelectedRepository
        {
            get { return this.selectedRepository; }
        }

        #region Constructors

        public RepositorySelectionForm(Repository selectedRepository)
        {
            InitializeComponent();

            this.selectedRepository = selectedRepository;
            this.SetUp();
            this.LoadData();
        }

        #endregion

        #region Private methods

        /// <summary>
        /// Setup the data grid
        /// </summary>
        private void SetUp()
        {
            this.repositoryRepository = Program.Container.Resolve<IRepository<Repository>>();
        }

        /// <summary>
        /// Load all repositories from database
        /// </summary>
        private void LoadData()
        {
            this.listOfRepositories = this.repositoryRepository.FindAll();
            if (this.listOfRepositories == null)
            {
                this.kcboRepositories.Enabled = false;
                this.btnOK.Enabled = false;
            }
            else
            {
                this.kcboRepositories.ValueMember = Repository.Properties.Id;
                this.kcboRepositories.DisplayMember = Repository.Properties.Name;
                this.kcboRepositories.DataSource = this.listOfRepositories;
                if (this.selectedRepository != null)
                {
                    this.kcboRepositories.SelectedItem = this.listOfRepositories.FirstOrDefault(repositoryItem => repositoryItem.Id.Equals(this.selectedRepository.Id));
                }
            }
        }

        #endregion

        #region Events

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.selectedRepository = this.kcboRepositories.SelectedItem as Repository;
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        #endregion

    }
}
